class FilmShort
    attr_accessor :id, :tytul, :tytul_oryg
    
    @@ksk_movies = []
    
    ISO = "ISO-8859-2//IGNORE"
    WIN = "WINDOWS-1250//IGNORE"
    UTF = "UTF-8//IGNORE"
    
    include FilmCommon
    
    def initialize(tytul, tytul_oryg = '', id = nil)
        @id = id
        @tytul = tytul
        @tytul_oryg = tytul_oryg
    end
    
    def to_film
        return nil if self.id.blank?
        Film.find(self.id)
    end
    
    def self.find_all_from_ksk_page
        short_films = []
        films = self.get_film_data
        films.each do |item|
            short_films << FilmShort.new(item[1], item[2], item[0])
        end
        short_films
    end

    def self.find_all_by_sql
        short_films = []
#        res = Film.find_by_sql("select ID_film, CAST(tytul AS CHAR CHARACTER SET utf8) COLLATE utf8_general_ci AS tyt, tytul_oryg from film order by ID_film desc")
        res = Film.find_by_sql("select ID_film, tytul AS tyt, tytul_oryg from film order by ID_film desc")        
        res.each do |item|
            tytul = item.attributes["tyt"] #Iconv.new(UTF, WIN).iconv(item.attributes["tyt"])
            short_films << FilmShort.new(tytul, item.attributes["tytul_oryg"], item.attributes["ID_film"])
        end
        short_films
    end

    def self.find_from_www(obce_id, kino_id, tytul, tytul_oryg = "")                                         ## checks if there is a film whith this title (orig_title)
      film_obcy = FilmObcy.find(:first, :conditions => ["obce_id = ? AND ID_kino = ?", obce_id, kino_id]) # || FilmObcy.find(:first, :conditions => ["tytul = ? OR tytul_oryg = ?", tytul, tytul_oryg])
      if film_obcy.nil?
          kino = Kino.find(kino_id)
          film_obcy = FilmObcy.find(:first, :conditions => ["obce_id = ? AND ID_kino IN (select ID_kino from kino where grupa_id = ?)", obce_id, kino.grupa_id]) unless kino.grupa_id.nil?
      end
      
      if film_obcy.nil?
          film_short = FilmShort.find_from_www_by_title(tytul, tytul_oryg)
          unless film_short.nil?
            film_obcy = FilmObcy.new
            film_obcy.ID_film = film_short.id
            film_obcy.ID_kino = kino_id
            film_obcy.obce_id = obce_id
            film_obcy.tytul = tytul
            film_obcy.tytul_oryg = tytul_oryg
            film_obcy.save          
          end
      else
          film_short = FilmShort.new(tytul, tytul_oryg, film_obcy.ID_film)      
      end
      film_short
    end

    def self.find_from_www_by_title(tytul, tytul_oryg = "")
        film_short = FilmShort.new(tytul, tytul_oryg)
        self.get_ksk_movies.each do |film_short_from_ksk|
          if (!film_short.tytul_oryg.blank? && film_short_from_ksk.title_orig_clean == film_short.title_orig_clean) ||
             (!film_short.tytul.blank? && film_short_from_ksk.title_clean == film_short.title_clean)
            return film_short_from_ksk
          end
        end
        RAILS_DEFAULT_LOGGER.debug("### Nie ma w bazie: #{film_short.inspect} ####")
        nil
    end
    
    def self.get_ksk_movies
      @@ksk_movies = find_all_by_sql if @@ksk_movies.length == 0
      @@ksk_movies
    end  
    
    private
    def self.get_film_data
      url = 'http://www.kino.krakow.pl/wstawki/film_exp.php'
      uri = URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      path = uri.path.dup # required so we don't modify path
      path << "?#{uri.query}" if uri.query  
      headers = {}
      response = http.request_get(path, headers)
      raise "Page does not exist" unless response.kind_of? Net::HTTPSuccess
      html = response.body 
      lines = html.split('###')
      short_films = []
      lines.each { |line|
          short_films << line.strip.split('#') if line.ends_with?("<br />")
      }
      short_films
    end
end